<?php

namespace App\Console\Commands\OpenShop\Nsq;

use App\Enums\Common\NsqEnum;
use App\Service\Activity\ShopActivityService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubKfosOrderMerchantOrderCreatedCommand extends Command
{
    protected $signature = 'openshop:nsq-sub-kfos.order.merchantOrder.created';

    protected $description = "activity:nsq - 订阅订货订单创建完成数据同步";

    public function handle()
    {
        ini_set('memory_limit', '4G');
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(
                NsqEnum::TOPIC_KFOS_MERCHANT_ORDER_CREATED, NsqEnum::CHANNEL_TIGER_MERCHANT_ORDER_CREATED_EVENT,
                function (Message $message) {
                    Log::info($this->description, $message->data());

                    try {
                        $data = $message->data();
                        $this->doHandle($data);
                    } catch (Exception $exception) {
                        logException($this->description, $exception, $message->data(), true, true);
                    } finally {
                        $message->done();
                    }
                }
            );

    }

    /**
     * @param array $data
     * @throws Exception
     */
    private function doHandle(array $data)
    {
        $id   = $data['id'] ?? 0;   // 订单id
        $uuid = $data['uuid'] ?? '';// uuid 关联活动参与

        if (!$id) {
            return;
        }

        // 消杀活动 订单创建完成-更新活动参与记录
        if ($uuid) {
            ShopActivityService::syncActivityJoinDetail($data);
        }


    }

}
